package COMP;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JPanel;

public class MakeImageFromPanel {

	private JPanel convertTargetPanel;
	private BufferedImage tempImage;
	private String filepath;
	private FileOutputStream fostemp;

	public MakeImageFromPanel(JPanel targetpanel, String filepath) {
		this.convertTargetPanel = targetpanel;
		this.filepath = filepath;
	}

	public void createImage() {
		int w = convertTargetPanel.getWidth();
		int h = convertTargetPanel.getHeight();
		BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		convertTargetPanel.paint(g);
		tempImage = bi;
	}

	public void convertImage() {

		try {
			fostemp = new FileOutputStream(filepath);
			BufferedOutputStream bout = new BufferedOutputStream(fostemp);
			ImageOutputStream ios = ImageIO.createImageOutputStream(bout);
			ImageIO.write(tempImage, "png", ios);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void FileClose(){
		try {
			fostemp.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
